<?php
class order extends userBase {
    function indexTask($page,$order_id=null){
        $this->listTask($page,$order_id);
    }
    function listTask($page,$order_id=null){
        $userId=$this->user->getLoginId();
        $page=$page>=1? $page: 1;
        $countOfPage=10;
        $offset=($page-1)*$countOfPage;
        list($result['list'],$total)=OrderMode::init()->getList($userId,null,null,null,null,null,null,null,$countOfPage,$offset);
        $url=WebRouter::init()->getQuestion("page=");
        $result['page']=new Page($page,$total,$countOfPage);
        $result['page']->setPageCallback(function($page)use($url){
            return $url.$page;
        });
        $result['pageEmpty']=$total==0?true:false;
        $result['currentId']=$order_id;
        View::displayAsHtml($result, "order-list.php");
    }
    function detailTask($id){
        $userId=$this->user->getLoginId();
        if(!OrderMode::init()->checkOrderBelongsToUser($id,$userId)){
            return new Intent(404,"非法操作");
        }
        $ad=AddressMode::init();
        $r=OrderMode::init()->getDetail($id);
        $userAddId=$r['order']['user_address_id'];
        $serviceId=$r['order']['service_id'];
        if(!empty($userAddId)){
            $r['userAddress']=$ad->getUserAddressAsString($userAddId);
        }
        if(!empty($serviceId)){
            $serviceInfo=ServiceMode::init()->getDetail($serviceId);
            if(!empty($serviceInfo)){
                $serviceAddId=$serviceInfo['address_id'];
                $addStr=$ad->getDetailAsString($serviceAddId);
                $serviceInfo['addressDetail']=$addStr;
                $r['service']=$serviceInfo;
                $c=CommentModule::init('service_comment','order_id','service_id');
                $r['service']['comment']=$c->getDetailByTowIds($id,$serviceId);
            }
        }
        View::displayAsHtml($r, "order-detail.php");
    }
    function confirmDirectTask($id,$attr_id,$number){
        $userId=$this->user->getLoginId();
        $r['userInfo']=UserMode::init()->getDetailWithoutJoin($userId);
        if($attr_id == null || $number == null){
            echo "非法操作";
            return false;
        }
        $g = GoodsMode::init();
        $goods=$g->getSimpleInfo($id);
        $goods['real_price']=$g->getPriceByNum($goods['price_id'],$number);
        $attrInfo=$g->getAttrDetail($attr_id);
        $goods['attr_name']=$attrInfo['name'];
        $goods['attr_id']=$attrInfo['id'];
        $goods['number']=$number;
        $goods['share']=$g->getShareDetail($userId,$id);
        $shop_id=$goods['shop_id'];
        $data['shop']=ShopMode::init()->getDetail($shop_id);
        $data['goods'][0]=$goods;
        $r['order'][0]=$data;
        $r['confirmType']='direct';
        $this->confirm($r);
    }
    function confirmCartTask($cartIds){
        if(empty($cartIds)){
            echo "非法操作";
            return false;
        }
        $c=CartMode::init();
        $userId=$this->user->getLoginId();
        $r['userInfo']=UserMode::init()->getDetailWithoutJoin($userId);
        $r=array();
        $data=array();
        foreach ($cartIds as $k=>$v) {
            $data['shop']=ShopMode::init()->getDetail($k);
            $data['goods']=$c->getList($userId,$v);
            $r['order'][]=$data;
        }
        $r['confirmType']='cart';
        $this->confirm($r);
    }
    function confirm($r){
        View::displayAsHtml($r, "order-confirm.php");
    }

    function confirmSubmitTask($confirmType,$shop,$order_amount,$payment_amount,$pay_way,
                               $user_address_id,$point,$user_coupon_id,$service_id,$buyer_id,
                               $money = 0.0,$code = null,$remark){
        $orderMode=OrderMode::init();
        $userId=$this->user->getLoginId();
        $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
        $flag=true;
        $order_ids_arr=array();
        $gopen_ids_arr=array();
        if(!empty($shop)){
            foreach ($shop as $k=>&$v) {
                $shop_id=(int)$v['shop_id'];
                foreach ($v['goods'] as $gV) {
                    $gopen_ids_arr[]=$gV['gopen_id'];
                    //分享人标记为购买
                    GoodsMode::init()->goodsShareBuy($gV['share_id']);
                    GoodsMode::init()->modifyStock($gV['gopen_id'],$gV['attr_id'],-$gV['number']);
                }
                if($k!=0){
                    $point=null;
                    $user_coupon_id=null;
                }
                $buyerId=UserMode::init()->getIdByUsername($buyer_id);
                $order_id=$orderMode->create($userId,$shop_id,$v['goods'],$v['type'],$v['order_amount'],
                    $v['payment_amount'],$user_address_id,$point,$user_coupon_id,$service_id,$buyerId,$remark);
                $v['order_id']=$order_id;
                $order_ids_arr[]=$order_id;
                $flag &= $order_id>0?true:false;
            }
        }else{
            $flag=false;
        }
        if($flag){//下单成功
            //删除购物车内相应商品
            if($confirmType=='cart'){
                CartMode::init()->removeByGopenIds($userId,$gopen_ids_arr);
            }
            $total_order_amount=0.0;
            $total_payment_amount=0.0;
            $allOrderAmountArr=OrderMode::init()->getAmountOfOrder($order_ids_arr);

            foreach ($allOrderAmountArr as $a_v) {
                $total_order_amount+=$a_v['order_amount'];
                $total_payment_amount+=$a_v['payment_amount'];
            }
            if($pay_way == 'money'){

                if($userInfo['money_usable'] == 0){
                    $result['message']="抱歉，您的余额支付已被冻结，您可以使用支付宝付款或联系客服";
                    View::displayAsHtml($result,"plugin/state/tips.php");
                    return;
                }//冻结跳转
                //直接在下单页开始支付
                //$order_ids=implode(',',$order_ids_arr);
                $okFlag = true;
                foreach ($order_ids_arr as $k => $v) {
                    //余额支付
                    $orderInfo=OrderMode::init()->getDetailWithoutJoin($v);
                    $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
                    $remark=OrderMode::init()->getRemarkOfOrder($v);
                    $history_id=MoneyMode::init()->add($userId,'支付订单'.$v,
                        -$orderInfo['payment_amount'],$userInfo['money']-$orderInfo['payment_amount'],date("Y-m-d H:i:s",time()).$remark,null,null,'money',0,$v);
                    $return=$this->moneyPay($userId,$history_id,$userInfo,$orderInfo);
                    if(strtolower($return) == 'success'){
                        $okFlag &= true;
                    }else{
                        $okFlag &= false;
                    }
                }

                $result['message']=$okFlag?"支付成功":"支付失败，请前往我的订单查看详情或者继续支付";
                //$result['message']="请填写验证码完成支付";
            }else{
                $order_ids=implode(',',$order_ids_arr);
                $event='充值';
                $history_id=MoneyMode::init()->add($userId,$event,$total_payment_amount,$userInfo['money']+$total_payment_amount,
                    date("Y-m-d H:i:s",time()).'充值',null,null,'alipay',0,$order_ids);
                $subject='充值余额'.$total_payment_amount.'元';
                $show_url=WebRouter::init()->getPage('order','list');
                $this->aliPay($history_id,$subject,$total_payment_amount,$show_url);
                return;
            }
        }else{//下单失败
            $result['message']="选购商品信息错误，请联系客服帮您解决问题";
        }
//        $result['url']=WebRouter::init()->getPage('order','list',"order_id={$order_id}");
        $result['url']=WebRouter::init()->getPage('order','list');
        View::displayAsHtml($result,"plugin/state/tips.php");
    }
    function userAddressTask(){
        $userId=$this->user->getLoginId();
        $addressMode=AddressMode::init();
        $r['data']['list']=$addressMode->getList($userId);
        foreach($r['data']['list'] as &$v){
            $v['address_string']=$addressMode->getUserAddressAsString($v['id']);
        }
        View::displayAsJson($r);
    }
    function addAddressTask($receiver,$phone,$address_id,$address_text){
        $userId=$this->user->getLoginId();
        $addressMode=AddressMode::init();
        $r['data']['address_id']=$addressMode->add($userId, $receiver,$phone,$address_id,$address_text);
        $r['state']=$r['data']['address_id']!=-1? DataMessage::STATE_SUCCESS: DataMessage::STATE_ERROR;
        View::displayAsJson($r);
    }
    function deleteAddressTask($id){
        $userId=$this->user->getLoginId();
        $addressMode=AddressMode::init();
        $addressData=$addressMode->getDetail($id);
        if(empty($addressData)&& $addressData['user_id']!=$userId){
            $r= new DataMessage(DataMessage::STATE_WARRING, "地址不存在 或 该用户地址不属于当前用户");
        }elseif($addressMode->delete($id)){
            $r= new DataMessage(DataMessage::STATE_SUCCESS, "删除成功");
        }else{
            $r= new DataMessage(DataMessage::STATE_ERROR, "删除失败");
        }
        View::displayDataMessage($r);
    }
    // TODO 还少了设为默认、修改（修改mode还没有），我建议这两个功能前端先不要，毕竟设计图没有

    function cancelTask($id){
        $o=OrderMode::init();
        $r=$o->cancel($id);
        $result['message']=$r?"取消订单成功":"取消订单失败";
        $result['url']=WebRouter::init()->getPage('order','list');
        View::displayAsHtml($result,"plugin/state/tips.php");
    }

    function payTask($pay_way='money',$order_id,$code){
        $userId=$this->user->getLoginId();
        $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
        $orderInfo=OrderMode::init()->getDetailWithoutJoin($order_id);
        if(empty($orderInfo)||$userInfo['user_id']!=$orderInfo['user_id']){
            $result['message']="订单信息错误，请联系客服解决问题";
            View::displayAsHtml($result,"plugin/state/tips.php");
            return;
        }
        if($pay_way=='money'){
            if($userInfo['money_usable'] == 0){
                $result['message']="抱歉，您的余额支付已被冻结，您可以使用支付宝付款或联系客服";
                View::displayAsHtml($result,"plugin/state/tips.php");
                return;
            }
            $loginInfo=$this->user->getLoginInfo();
            $tel=$loginInfo['username'];
            $checkResult=$this->user->checkCode($tel,$code);
            if($checkResult->state!=200){
                $result['message']=$checkResult->title;
                View::displayAsHtml($result,"plugin/state/tips.php");
                return;
            }
            //余额支付
            $remark=OrderMode::init()->getRemarkOfOrder($order_id);
            $history_id=MoneyMode::init()->add($userId,'支付订单'.$order_id,
                    -$orderInfo['payment_amount'],$userInfo['money']-$orderInfo['payment_amount'],date("Y-m-d H:i:s",time()).$remark,null,null,'money',0,$order_id);
            $return=$this->moneyPay($userId,$history_id,$userInfo,$orderInfo);
            if(strtolower($return) == 'success'){
                $result['message']="支付成功";
            }else{
                $result['message']=$return;
            }
            $result['url']=WebRouter::init()->getPage('order','list');
            View::displayAsHtml($result,"plugin/state/tips.php");
            return;
        }else{
            //支付宝支付
            $history_id=MoneyMode::init()->getHistoryIdOfOrderId($order_id);
            if(empty($history_id)){

                $history_id=MoneyMode::init()->add($userId,'充值余额', $orderInfo['payment_amount'],
                    $userInfo['money']+$orderInfo['payment_amount'],date("Y-m-d H:i:s",time()).'充值',null,null,'alipay',0,$orderInfo['id']);
            }
            $subject='充值余额'.$orderInfo['payment_amount'].'元';
            $show_url=WebRouter::init()->getPage('order','list');
            $this->aliPay($history_id,$subject,$orderInfo['payment_amount'],$show_url);
            //能不能跳到支付宝别回来了
            return;
        }
    }
    //余额付款
    function moneyPay($userId,$history_id,$userInfo,$orderInfo){
        if($userInfo['money']>=$orderInfo['payment_amount']){
            $payR=MoneyMode::init()->moneyPay($userId,$orderInfo['payment_amount'],$orderInfo['payment_amount']);
            if($payR){  //余额支付成功
                $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
                $this->handingUserInfo($userId,$userInfo['point'],$orderInfo['point'],
                    $orderInfo['id'],$orderInfo['user_coupon_id'],$orderInfo['order_amount'],
                    $orderInfo['payment_amount'],$orderInfo['type']);
                MoneyMode::init()->setSuccessSymbol($history_id,null,$userInfo['money'],1);
                return 'success';
            }else{
                return '支付失败，系统开小差了,请重试';
            }
        }else{

            $history_id=MoneyMode::init()->add($userId,'充值余额', $orderInfo['payment_amount'],
                $userInfo['money']+$orderInfo['payment_amount'],date("Y-m-d H:i:s",time()).'充值',null,null,'alipay',0,$orderInfo['id']);
            $surplus=$orderInfo['payment_amount']-$userInfo['money'];
            $subject='充值余额'.$orderInfo['payment_amount'].'元';
            $show_url=WebRouter::init()->getPage('order','list');
            $this->aliPay($history_id,$subject,$surplus,$show_url);
            return '您的余额不够哦，需先进行支付宝充值不足金额';
        }
    }
    function aliPay($out_trade_no,$subject,$total_fee,$show_url){
        $result['WIDout_trade_no']=$out_trade_no;
        $result['WIDtotal_fee']=$total_fee;
        $result['WIDsubject']=$subject;
        $result['WIDshow_url']=$show_url;
        View::displayAsHtml($result,'../alipay/alipayapi.php');
    }
    function return_urlTask(){
        require_once("alipay/alipay.config.php");
        require_once("alipay/lib/alipay_notify.class.php");
        $alipayNotify = new AlipayNotify($alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if($verify_result) {//验证成功
            //商户订单号
            $out_trade_no = $_GET['out_trade_no'];//history_id
            //支付宝交易号
            $trade_no = $_GET['trade_no'];
            //交易状态
            $trade_status = $_GET['trade_status'];

            if($_GET['trade_status'] == 'TRADE_FINISHED' || $_GET['trade_status'] == 'TRADE_SUCCESS') {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                $moneyMode = MoneyMode::init();
                $url=WebRouter::init()->getPage('order','list');
                //商户信息未处理：这里我只检查了history，没有检查每一个订单的情况
                if(!$moneyMode->checkHistoryDealed($out_trade_no)){
                    //处理订单已经用户各种信息
                    $userId=$this->user->getLoginId();
                    $moneyMode->updateMoney($userId,$_GET['total_fee'],true);
                    $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
                    $order_ids=$moneyMode->getOrderIdsById($out_trade_no);
                    if(!empty($order_ids)){
                        $moneyMode->setSuccessSymbol($out_trade_no,$trade_no,$userInfo['money'],1);
                        $order_ids_arr=explode(',',$order_ids);
                        foreach ($order_ids_arr as $v) {
                            $order_id=$v;
                            $userInfo = UserMode::init()->getDetailWithoutJoin($userId);
                            $orderInfo=OrderMode::init()->getDetailWithoutJoin($order_id);
                            $payR=$moneyMode->moneyPay($userId,$orderInfo['payment_amount'],$orderInfo['payment_amount']);
                            if($payR){  //余额支付成功
                                $this->handingUserInfo($userId,$userInfo['point'],$orderInfo['point'],
                                    $orderInfo['id'],$orderInfo['user_coupon_id'],$orderInfo['order_amount'],
                                    $orderInfo['payment_amount'],$orderInfo['type']);
                                $remark=OrderMode::init()->getRemarkOfOrder($order_id);
                                $moneyMode->add($userId,'支付订单'.$order_id, -$orderInfo['payment_amount'],
                                    $userInfo['money']-$orderInfo['payment_amount'], date("Y-m-d H:i:s",time()).$remark,
                                    null,null,'money',1,$order_id);//生成流水记录
                            }
                        }
                        $url=WebRouter::init()->getPage('order','list');
                    }else{//仅充值
                        $moneyMode->setSuccessSymbol($out_trade_no,$trade_no,$userInfo['money'],1);
                        $url=WebRouter::init()->getPage('my','account');
                    }
                }
            }
            else {
                echo "trade_status=".$_GET['trade_status'];
            }
            $return = true;
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
        } else {
            $moneyPayRST=false;
            //验证失败
            //如要调试，请看alipay_notify.php页面的verifyReturn函数
            $return= false;
            $url=WebRouter::init()->getPage('order','list');//失败了返回页面
        }
        header("Location:".$url);
        return;
    }
    //处理各种支付后的用户增长值
    function handingUserInfo($userId,$userPoint,$point,$order_id,$user_coupon_id,
                                       $order_amount,$payment_amount,$type){
        $state=$type=='normal'?'unshipped':'unused';
        OrderMode::init()->setState($order_id,$state);
        if(!empty($point)){
            //判断point<=paymen_amount*10%
            $point = $point<=$order_amount*10.0? $point : $order_amount*10.0;
            $point = $point > $userPoint? $userPoint:$point;
            PointMode::init()->usePoint($userId,$point,'订单'.$order_id.'使用积分',$payment_amount);
        }
        if(!empty($user_coupon_id)){
            CouponMode::init()->using($user_coupon_id,$order_id);
        }
        //支付成功，积分要涨，成长值要涨
        if((int)$payment_amount>0){
            PointMode::init()->earnPoint($userId,(int)$payment_amount,'购买获得积分',$payment_amount);
            $id=UserMode::init()->getIdByUserId($userId);
            UserMode::init()->modifyGrowth($id,$payment_amount,true);
        }
        return; //不知道应该返回什么 TODO
    }
    function addCashTask($value){
        if(empty($value)||round($value,2)<=0.0){
            $r['message']='金额不合法';
            View::displayAsHtml($r,"plugin/state/tips.php");
            return;
        }
        $userId=$this->user->getLoginId();
        $userInfo=UserMode::init()->getDetailWithoutJoin($userId);
        $currentDate = date("Y-m-d H:i:s",time());
        $remark=$currentDate.'充值';//TODO
        $history_id=MoneyMode::init()->add($userId,'充值余额',
            $value,$userInfo['money']+$value,$remark,null,null,'alipay');
        if($history_id>0){
            $subject='充值';
            $show_url=WebRouter::init()->getPage('my','account');
            $this->aliPay($history_id,$subject,round($value,2),$show_url);
            return;
        }else{
            $r['message']='出错了，请重试';
            View::displayAsHtml($r,"plugin/state/tips.php");
            return;
        }
    }
}